using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace WPFTemplateLib.Adorners
{
	/// <summary>
	/// 可绑定的容器型的装饰器（DataContext 与被装饰元素的相同）
	/// 修改自：Microsoft.Xaml.Behaviors.Layout.AdornerContainer
	/// </summary>
	public class BindableContainerAdorner : Adorner
	{
		/// <inheritdoc />
		public BindableContainerAdorner(UIElement adornedElement) : base(adornedElement)
		{
		}

		private FrameworkElement _child;
		public FrameworkElement Child
		{
			get { return _child; }
			set
			{
				AddVisualChild(value);
				_child = value;
				Child.DataContext = (AdornedElement as FrameworkElement)?.DataContext;
			}
		}

		/// <inheritdoc />
		protected override Size ArrangeOverride(Size finalSize)
		{
			if(_child != null)
			{
				_child.Arrange(new Rect(finalSize));
			}

			return finalSize;
		}

		/// <inheritdoc />
		protected override int VisualChildrenCount
		{
			get { return _child == null ? 0 : 1; }
		}

		/// <inheritdoc />
		protected override Visual GetVisualChild(int index)
		{
			return index == 0 && _child != null ? _child : base.GetVisualChild(index);
		}
	}
}
